<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
// $wechatObj->valid();
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
	public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		
		//extract post data
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$msgType = $postObj->MsgType;
			
			//创建文本消息回复
			$textRespTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>";
				
			$fromUserName = $postObj->FromUserName;
			$toUserName = $postObj->ToUserName;
			$time = time();
			$msgType = "text";
			$contentStr = "Welcome to wechat world!";
			
			//根据消息类型处理
			switch($msgType)
			{
				case "text":
					//文本消息
					$resultStr = $this->handleText($postObj);
					break;
				case "image":
					//图片消息
					$resultStr = $this->handleImage($postObj);
					break;
				case "voice":
					//语音消息
					$resultStr = $this->handleVoice($postObj);
					break;
				case "video":
					//视频消息
					$resultStr = $this->handleVideo($postObj);
					break;
				case "location":
					//地理位置消息
					$resultStr = $this->handleLocation($postObj);
				case "link":
					//链接消息
					$resultStr = $this->handleLink($postObj);
				default:
					$resultStr = "Unkonwn msgType:".$msgType;
					break;
			}
			
			$textResp = sprintf($textRespTpl, $fromUsername, $toUsername, $time, $msgType, $resultStr);
			echo $textResp;
        }else {
        	echo "";
        	exit;
        }
    }
	
    
	public function handleText($postObj)
	{
		$resultStr = "消息错误";
		
		$keyword = trim($postObj->Content);
		if(!empty( $keyword ))
		{
			$resultStr = "Welcome to wechat world!";
		}
		return $resultStr;
	}
	
	
	public function handleImage($postObj)
	{
		
	}
	
	
	public function handleVoice($postObj)
	{
		
	}
	
	
	public function handleVideo($postObj)
	{
	
	}
	
	
	public function handleLocation($postObj)
	{
	
	}
	
	
	public function handleLink($postObj)
	{
	
	}
	
	
	
	
	
	
	
	
	
	public function valid()
	{
		$echoStr = $_GET["echostr"];
		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}
	
	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
	
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
	
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}
?>
